About 1998 letters

About 10 minutes

#Python's usage of regular expressions

In Python, regular expressions are used via the re module. Since regular expressions have their own escape syntax, it’s common to use Python raw strings to avoid double escaping.

FunctionDescriptionExample
matchChecks if the string matches the pattern from the beginningSee below
searchSearches for a substring matching the patternSee below
subReplaces substrings that match the patternSee below
splitSplits string using substrings that match the patternSee below
compileCompiles a pattern for reuseSee below

#Pattern Matching

import re

# Validate email format
email_pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
if re.match(email_pattern, "[email protected]"):
    print("Valid email")

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#Text Search

import re

text = "Order ID: 12345, Date: 2023-08-15"
match = re.search(r'Order ID: (\d+), Date: (\d{4}-\d{2}-\d{2})', text)
if match:
    print(0, match.group(0))
    print(1, match.group(1))
    print(2, match.group(2))

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#Text Replacement

import re

text = "Username: user Password: 123456"
hidden = re.sub(r'\d{6}', '******', text)
print(hidden)

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#Text Splitting

import re

data = "Apple, Banana, Orange, Grape"
fruits = re.split(r',\s*', data)  # Split by comma, allowing optional space after
print(fruits)  # Output: ['Apple', 'Banana', 'Orange', 'Grape']

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#Compiling Regular Expressions

Compiling a pattern improves efficiency when used multiple times.

import re

# Compile email pattern
email_pattern = re.compile(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$')
if email_pattern.match("[email protected]"):
    print("Valid email")

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

Updated: 5/21/2025

Author: PlanC

Created: 5/15/2025